<template>
  <!-- 新增部门的弹层 -->
  <el-dialog :title="title" :visible="showDialog" @close="btnCancel">
    <!-- 表单组件  el-form   label-width设置label的宽度   -->
    <!-- 匿名插槽 -->
    <el-form v-if="showDialog" ref="deptForm" :model="formData" :rules="rules" label-width="120px">
      <el-form-item label="部门名称" prop="name">
        <el-input
          v-model="formData.name"
          style="width: 80%"
          placeholder="1-50个字符"
        />
      </el-form-item>
      <el-form-item label="部门编码" prop="code">
        <el-input
          v-model="formData.code"
          style="width: 80%"
          placeholder="1-50个字符"
        />
      </el-form-item>
      <el-form-item label="部门负责人" prop="manager">
        <el-select
          v-model="formData.manager"
          style="width: 80%"
          placeholder="请选择"
          @focus="getEmployeeSimple"
          @blur="checkManager"
        >
          <el-option
            v-for="person in people"
            :key="person.id"
            :label="person.username"
            :value="person.username"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="部门介绍" prop="introduce">
        <el-input
          v-model="formData.introduce"
          style="width: 80%"
          placeholder="1-300个字符"
          type="textarea"
          :rows="3"
        />
      </el-form-item>
    </el-form>
    <!-- el-dialog有专门放置底部操作栏的 插槽  具名插槽 -->
    <el-row slot="footer" type="flex" justify="center">
      <!-- 列被分为24 -->
      <el-col :span="6">
        <el-button type="primary" size="small" @click="btnOK">确定</el-button>
        <el-button size="small" @click="btnCancel">取消</el-button>
      </el-col>
    </el-row>
  </el-dialog>
</template>

<script>
import { getDepartments, addDepartments, getDepartDetail, updateDepartments } from '@/api/departments'
import { getEmployeeSimple } from '@/api/employees'
export default {
  props: {
    showDialog: {
      type: Boolean,
      default: false
    },
    node: {
      type: Object,
      default() {
        return {}
      }
    }
  },
  data() {
    const checkNameRepeat = async(rule, value, callback) => {
      // 检查在同级(属于同一个父部门)不能同名
      // 1. 获取全部部门数据
      const { depts } = await getDepartments()

      let isRepeat
      if (this.formData.id) {
        // 还有编辑场景
        // 判断是否同名
        // 1 将同一父部门的结果筛选出来
        // 2. 将自己排除在外的同时, 找出跟自己同名的结果
        isRepeat = depts
          .filter(item => item.pid === this.node.pid)
          .some(item => item.name === value && item.id !== this.formData.id)
      } else {
        // 这里是新增场景
        // 2. 校验是否存在同名
        // 2.1 先将同一父部门的结果筛选出来
        // 2.2 在这些结果中看看有没有跟 value 一样
        isRepeat = depts
          .filter((item) => item.pid === this.node.id)
          .some((item) => item.name === value)
      }

      isRepeat ? callback(new Error('同一部门下不能重名')) : callback()
    }
    const checkCodeRepeat = async(rule, value, callback) => {
      // 1. 获取全部部门数据
      const { depts } = await getDepartments()
      // 2. 校验是否重复 Code
      const isRepeat = depts.some((item) => item.code === value && item.id !== this.formData.id)
      isRepeat ? callback(new Error('部门编码必须唯一')) : callback()
    }
    return {
      formData: {
        name: '',
        code: '',
        manager: '',
        introduce: ''
      },
      rules: {
        name: [
          { required: true, message: '该项不能为空', trigger: 'blur' },
          {
            trigger: 'blur',
            min: 1,
            max: 50,
            message: '部门名称要求1-50个字符'
          },
          { trigger: 'blur', validator: checkNameRepeat }
        ],
        code: [
          { required: true, message: '该项不能为空', trigger: 'blur' },
          {
            trigger: 'blur',
            min: 1,
            max: 50,
            message: '部门编码要求1-50个字符'
          },
          { trigger: 'blur', validator: checkCodeRepeat }
        ],
        manager: [{ required: true, message: '该项不能为空', trigger: 'blur' }],
        introduce: [
          { required: true, message: '该项不能为空', trigger: 'blur' },
          {
            trigger: 'blur',
            min: 1,
            max: 300,
            message: '部门介绍要求1-300个字符'
          }
        ]
      },
      people: []
    }
  },
  computed: {
    title() {
      return this.formData.id ? '编辑部门' : '新增部门'
    }
  },
  methods: {
    async getEmployeeSimple() {
      this.people = await getEmployeeSimple()
    },
    async btnOK() {
      try {
        console.log(this.formData)
        // 校验表单
        await this.$refs.deptForm.validate()
        // 发送请求
        console.log('真的发送请求')
        // 需要判断, 到底是新增还是编辑
        if (this.formData.id) {
          // 编辑
          await updateDepartments(this.formData)
        } else {
          // 新增
          await addDepartments({ ...this.formData, pid: this.node.id })
        }
        // 提醒父页面更新数据
        this.$emit('addDepts')
        // 关闭当前弹窗
        // 不能直接改 props
        // this.showDialog = false
        // 应该通知父页面进行变更
        // this.$emit('xxx')
        // 另外还可以用固定写法, 配合父组件的 .sync 修饰符, 方便修改
        this.$emit('update:showDialog', false)
        // 弹窗提示
        this.$message.success('操作成功')
      } catch (error) {
        console.log('失败')
        console.log(error)
      }
    },
    btnCancel() {
      // 手动清理一下表单, 避免回显时的额外数据残留
      this.formData = {
        name: '',
        code: '',
        manager: '',
        introduce: ''
      }
      // 这个重置数据的函数
      // 1. 清楚各种校验错误提示
      // 2. 清楚表单绑定的所有数据
      this.$refs.deptForm.resetFields()
      this.$emit('update:showDialog', false)
    },
    checkManager() {
      setTimeout(() => {
        console.log(this.formData.manager)
        console.log('失去焦点')
        this.$refs.deptForm.validateField('manager')
      }, 200)
    },
    async getDepartDetail(id) {
      this.formData = await getDepartDetail(id)
    }
  }
}
</script>

<style>
</style>
